package com.example.demo.service;

import com.example.demo.entity.ImageRecognitionHistory;
import com.example.demo.mapper.ImageRecognitionHistoryMapper;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class ImageService {

    @Value("${image.upload-dir}")
    private String uploadDir;

    private static final String API_KEY = "jCA8TzPI9SpRCxfivGFzh3OA";
    private static final String SECRET_KEY = "xoO4CoPlmoV7alpGCbVzY8fMGYu2VwLI";
    private static final String UPLOAD_DIR = "G:/assignment-2/excellent/src/main/resources/images";  // 修改为实际路径
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Autowired
    private ImageRecognitionHistoryMapper historyMapper;

    // 上传图片并保存
    public Map<String, Object> uploadImage(MultipartFile file) throws IOException {
        String fileName = UUID.randomUUID().toString() + ".jpg";
        Path destinationPath = Paths.get(uploadDir, fileName);
        // 保存文件
        Files.copy(file.getInputStream(), destinationPath, StandardCopyOption.REPLACE_EXISTING);

        // 返回文件信息
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("fileName", fileName);
        return response;
    }

    // 图片识别
    public Map<String, Object> recognizeImage(String fileName) throws IOException {
        String imagePath = Paths.get(UPLOAD_DIR, fileName).toString();
        String base64Image = getFileContentAsBase64(imagePath, true);

        // 请求百度图片识别API
        String accessToken = getAccessToken();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image=" + base64Image);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();

        // 解析返回的识别结果
        JSONObject jsonResponse = new JSONObject(responseBody);
        JSONArray resultArray = jsonResponse.getJSONArray("result");

        // 提取关键词
        List<String> keywords = new ArrayList<>();
        for (int i = 0; i < resultArray.length(); i++) {
            JSONObject resultItem = resultArray.getJSONObject(i);
            String keyword = resultItem.getString("keyword");
            keywords.add(keyword);
        }

        // 保存识别结果到数据库
        saveRecognitionHistory(fileName, keywords);

        // 返回识别结果中的关键词
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("result", keywords);
        return responseMap;
    }

    // 保存识别历史记录到数据库
    private void saveRecognitionHistory(String fileName, List<String> keywords) {
        ImageRecognitionHistory history = new ImageRecognitionHistory();
        history.setFileName(fileName);
        history.setRecognitionResult(String.join(", ", keywords));  // 将关键词合并为一个字符串
        history.setUploadTime(LocalDateTime.now());

        historyMapper.insertHistory(history);  // 保存到数据库
    }

    // 获取历史记录
    public List<ImageRecognitionHistory> getHistory() {
        return historyMapper.getAllHistory();  // 查询数据库中所有历史记录
    }

    // 获取文件内容的 Base64 编码
    private String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(bytes);
        if (urlEncode) {
            base64 = java.net.URLEncoder.encode(base64, "UTF-8");
        }
        return base64;
    }

    // 获取 Access Token
    private String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
